package com.hcb.tonguetiphealth.widget.bookOnline;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.GeneralPageAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.ResDish;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.DishOrderActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.BottomWidget;
import com.hcb.tonguetiphealth.widget.GeneralWidget;
import com.hcb.tonguetiphealth.widget.recommendhealth.RecommendHealthWidget;

public class DishInfoWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "DishInfoWidget";
	private String url = Global.URL + Global.servlet_wineInfo;
	private Activity ctx;
	private LayoutInflater inflater;
	private Handler mHandler;
	private List<ResDish> dishList;
	private ResDish dish;
	private ImageView iv, iv1, iv2, iv3, iv4, iv5, iv6;
	
	private TextView tvName, tvDietGroup, tvPrice, tvKw, tvYyjz, tvSh, tvDetailInfo;
	private LinearLayout llBack, llAdd, llBooked, llComment, llDishOrder;
	private EditText bookNum;
	private ImageView dishImg, uporDownImg;
	 
	private int crrentPageId = 0;
	
	private ViewPager viewPager;
	private List<View> pageViews;
	private View view;
	private GeneralPageAdapter pageAdapter;
	
	private String FromWidgetFlag;
	private String dishId;
	private String resId;
	
	private Spanned sp;
	
	
	public DishInfoWidget(Context context) {
		super(context);
		ctx = (Activity)context;
				
		inflater = ctx.getLayoutInflater();
		inflate(context, R.layout.online_book_dish_info, this); 
		//FromWidgetFlag:从在线预订页过来为onlineBook；
		FromWidgetFlag = ctx.getIntent().getStringExtra("FromWidgetFlag");
		dishId = ctx.getIntent().getStringExtra("dishId");
		resId = ctx.getIntent().getStringExtra("resId");
		
		new BottomWidget(ctx, this);
		dishList = Global.resDishList;
		bindView();
		bindEvent();
		initData();
		initDataPageView();
	}
	
	private void bindView(){
		tvName = (TextView)findViewById(R.id.book_online_dish_info_name_textview);
		tvDietGroup = (TextView)findViewById(R.id.book_online_dish_info_diet_group_textview);
		tvPrice = (TextView)findViewById(R.id.book_online_dish_info_price_edittext);
		tvKw = (TextView)findViewById(R.id.online_book_dish_info_kw_textview);
		tvYyjz = (TextView)findViewById(R.id.online_book_dish_info_yyjz_textview);
		tvSh = (TextView)findViewById(R.id.online_book_dish_info_sh_textview);
		tvDetailInfo = (TextView)findViewById(R.id.online_book_dish_info_tv);

		dishImg = (ImageView)findViewById(R.id.book_online_dish_info_img);
		uporDownImg = (ImageView)findViewById(R.id.res_book_res_content_upordown);

		llBack = (LinearLayout)findViewById(R.id.online_book_info_back_linearlayout);
		bookNum = (EditText)findViewById(R.id.book_online_dish_info_hpone_edittext);
		
		llAdd = (LinearLayout)findViewById(R.id.book_online_dish_info_add_linearlout);
		llBooked = (LinearLayout)findViewById(R.id.book_online_dish_info_booked_button);
		llComment = (LinearLayout)findViewById(R.id.online_book_dish_content_linearlayout);
		llDishOrder = (LinearLayout)findViewById(R.id.onlie_book_dish_order_button);
		
		
		viewPager = (ViewPager)findViewById(R.id.book_online_dish_info_viewpager);
		
		boolean exit = false;
		for (int i = 0; i < Global.resDishOrderList.size(); i++) {
			ResDish tempDish  = Global.resDishOrderList.get(i);
			if (tempDish.getId().equals(dishId)) {
				bookNum.setText(tempDish.getOrderNum());
				exit = true;
				break;
			}
		}
		if (!exit) {
			llBooked.setVisibility(View.GONE);
		}else {
			llBooked.setVisibility(View.VISIBLE);
		}
	}
	
	private void bindEvent(){
		llBack.setOnClickListener(this);
		llAdd.setOnClickListener(this);
		llBooked.setOnClickListener(this);
		llComment.setOnClickListener(this);
		llDishOrder.setOnClickListener(this);
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在获取菜品信息...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					setDishInfo();
					dismissMessageDialog();
					break;
				case MessageWhat.NETWORK_FAILD:
					try {
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				 
				}
			}
		};
	}
	
	public void onClick(View v) {
		switch(v.getId()) {
		 
		case R.id.online_book_info_back_linearlayout:
			if ("onlineBook".equals(FromWidgetFlag)) {
				BookOnlineWidget widget = new BookOnlineWidget(ctx);
				ctx.getIntent().putExtra("resId", resId);
				ctx.setContentView(widget);
			} else {
				ctx.setContentView(new RecommendHealthWidget(ctx));
			}
			break;
		case R.id.online_book_dish_content_linearlayout:
			int viewVisibility = tvDetailInfo.getVisibility();
			if (viewVisibility == View.GONE || viewVisibility == View.INVISIBLE) {
				uporDownImg.setBackgroundResource(R.drawable.close_more);
				tvDetailInfo.setVisibility(View.VISIBLE);
			}else {
				uporDownImg.setBackgroundResource(R.drawable.open_more);
				tvDetailInfo.setVisibility(View.GONE);
			}
			break;
		case R.id.book_online_dish_info_add_linearlout:
			int intBookNum = Integer.parseInt(bookNum.getText().toString());
			if (intBookNum > 0) {
				boolean exit = false;
				for (int i = 0; i < Global.resDishOrderList.size(); i++) {
					ResDish tempDish = Global.resDishOrderList.get(i);
					if (dishId.equals(tempDish.getId())) {
						Global.resDishOrderList.get(i).setOrderNum(bookNum.getText().toString());
						exit = true;
						break;
					}
				}
				if (!exit) {
					dish.setOrderNum(bookNum.getText().toString());
					Global.resDishOrderList.add(dish);
				}
				showMessage(ctx, "已加入菜单");
				llBooked.setVisibility(View.VISIBLE);
			}else if(intBookNum == 0){
				showMessage(ctx, "订购分数不能为0！");
			}
			break;
		case R.id.onlie_book_dish_order_button:
			 Intent intent = new Intent(ctx, DishOrderActivity.class);
			 intent.putExtra("resId", resId);
			 ctx.startActivity(intent);
			break;
		case R.id.book_online_dish_info_booked_button:
			break;
		default:
			initDishInfo(v.getId());
			break;
		}
	}
	
	private void setDishInfo(){
		loadImage(dishImg, dish.getDishThumb());
		tvName.setText(dish.getTitle());
		
		tvDietGroup.setText("false".equals(dish.getDiet_group())?"":dish.getDiet_group());
		
		tvDetailInfo.setText(sp);
		tvKw.setText(dish.getKw());
		tvYyjz.setText(dish.getYyjz());
		tvSh.setText(dish.getSh());
		float fPrice = StringUtils.parseFloat(dish.getPrice());
		tvPrice.setText(" " + (int)(fPrice*0.9) + " ~ " + (int)(fPrice*1.1));
		
	}
	
	private void initDishInfo(int id) {
		int num = 0;
		switch(id) {
		case R.id.drinks_book_drink_info_pageview_img1:
			num += 0;
			break;
		case R.id.drinks_book_drink_info_pageview_img2:
			num += 1;
			break;
		case R.id.drinks_book_drink_info_pageview_img3:
			num += 2;
			break;
		case R.id.drinks_book_drink_info_pageview_img4:
			num += 3;
			break;
		case R.id.drinks_book_drink_info_pageview_img5:
			num += 4;
			break;
		case R.id.drinks_book_drink_info_pageview_img6:
			num += 5;
			break;
		}
		int position = crrentPageId*6 + num;
		ResDish dish = dishList.get(position);
		if (dishId == dish.getId()) {
			showMessage(ctx, "已是当前菜品");
		}else {
			this.dishId = dish.getId();
			initData();
		}
		
	}
 
	private void initData() {
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		dish = new ResDish();
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("userid", dishId));
					System.out.println("userid"+dishId);
					response = HttpUtils.Post(Global.getServletresdishinfo(), params);
					if(Global.DEBUG) {
						System.out.println("-----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if (!StringUtils.isEmpty(response)) {
					try {
						JSONObject jsonObject = new JSONObject(response);
						String strReturn = jsonObject.getString("return")
								.trim();
						if (strReturn.equals("true")) {
							JSONObject jObjectResult = jsonObject
									.getJSONObject("results");
							dish.setId(jObjectResult.getString("itemid"));
							dish.setTitle(jObjectResult.getString("title"));
							dish.setDiet_group(jObjectResult
									.getString("diet_group"));
							dish.setDishThumb(jObjectResult.getString("thumb"));
							dish.setContent(jObjectResult.getString("content"));
							dish.setKw(jObjectResult.getString("kw"));
							dish.setYyjz(jObjectResult.getString("yyjz"));
							dish.setSh(jObjectResult.getString("sh"));
							dish.setPrice(jObjectResult.getString("price"));
						}

					} catch (JSONException e) {
						Log.e(TAG, "dishinfo_json", e);
					} catch (Exception e) {
						Log.e(TAG, "dishinfo_json", e);
					}
					try {
						String html = dish.getContent();
						sp = Html.fromHtml(html, new Html.ImageGetter() {
							@Override
							public Drawable getDrawable(String source) {
								InputStream is = null;
								try {
									is = (InputStream) new URL(source).getContent();
									Drawable d = Drawable.createFromStream(is, "src");
//									d.setBounds(0, 0, d.getIntrinsicWidth(),
//											d.getIntrinsicHeight());
									d.setBounds(0, 0, 250,//图片宽度、高度设置
											150);
									is.close();
									return d;
								} catch (Exception e) {
									return null;
								}
							}
						}, null);
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
				
			}
		}.start();
	}
	private void initDataPageView() {
 
		pageViews = new ArrayList<View>();
		int pageCount = dishList.size()/6 + (dishList.size()%6 == 0?0:1);
		for(int i=0; i< pageCount; i++) {
			pageViews.add(inflater.inflate(R.layout.drinks_book_drinks_info_pageview, null));
		}
		
		ResDish dish;
		
		for(int i=0; i<pageViews.size(); i++) {
			view = pageViews.get(i);
			iv1 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img1);
			iv2 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img2);
			iv3 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img3);
			iv4 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img4);
			iv5 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img5);
			iv6 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img6);
			int count = dishList.size() - (i+1)*6;
			if(count >= 0) {
				for(int j=1; j<=6; j++) {
					dish = dishList.get(i*6 + j-1);
					initImage(j, dish);
				}
			} else {
				count = dishList.size() - i*6;
				for(int j=1; j<=count; j++) {
					dish = dishList.get(i*6 + j-1);
					initImage(j, dish);
				}
				switch(count) {
				case 1:
					iv2.setVisibility(ImageView.INVISIBLE);
					iv3.setVisibility(ImageView.INVISIBLE);
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 2:
					iv3.setVisibility(ImageView.INVISIBLE);
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 3:
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 4:
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 5:
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				}
			}
			
		}
		
		pageAdapter = new GeneralPageAdapter(pageViews);
		viewPager.setAdapter(pageAdapter);
		viewPager.setOnPageChangeListener(new GuidePageChangeListener());
	}
	private void initImage(int id,ResDish dish) {
		switch(id) {
		case 1:
			loadImage(iv1, dish.getDishThumb());
			iv1.setOnClickListener(this);
			break;
		case 2:
			loadImage(iv2, dish.getDishThumb());
			iv2.setOnClickListener(this);
			break;
		case 3:
			loadImage(iv3, dish.getDishThumb());
			iv3.setOnClickListener(this);
			break;
		case 4:
			loadImage(iv4, dish.getDishThumb());
			iv4.setOnClickListener(this);
			break;
		case 5:
			loadImage(iv5, dish.getDishThumb());
			iv5.setOnClickListener(this);
			break;
		case 6:
			loadImage(iv6, dish.getDishThumb());
			iv6.setOnClickListener(this);
			break;
		}
	}
	// 指引页面更改事件监听器
	class GuidePageChangeListener implements OnPageChangeListener {

		public void onPageScrollStateChanged(int arg0) {
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageSelected(int arg0) {
			crrentPageId = arg0;
			switch(arg0) {
			case 0:
				break;
			case 1:
				break;
			case 2:
				break;
			}
		}
	}
	@Override
	public void notifyAdapter() {
		
	}
}
